using UniversalAdmin.Domain.Entities.App;
using UniversalAdmin.Domain.Repositories;
using UniversalAdmin.Shared.Interface;
using UniversalAdmin.Application.Dtos.User;
using UniversalAdmin.Application.Dtos;

namespace UniversalAdmin.Application.Services;

public class AuthService : IAuthService
{
    private readonly IRepositories<User> _userRepo;
    private readonly IRepositories<Role> _roleRepo;
    private readonly IJwtService _jwtService;

    public AuthService(IRepositories<User> userRepo, IRepositories<Role> roleRepo, IJwtService jwtService)
    {
        _userRepo = userRepo;
        _roleRepo = roleRepo;
        _jwtService = jwtService;
    }

    public async Task RegisterAsync(UsersDto dto)
    {
        // 1. 检查用户名是否存在
        var exists = (await _userRepo.GetAllAsync()).Any(u => u.Username == dto.Username);
        if (exists) throw new Exception("用户名已存在");

        // 2. 生成盐和加密密码
        var hashedPwd = HashPassword(dto.Password);

        // 3. 查找默认角色（普通用户角色）
        var defaultRole = (await _roleRepo.GetAllAsync()).FirstOrDefault(r => r.Name == "普通用户");
        if (defaultRole == null)
        {
            throw new Exception("默认角色不存在，请确保数据库中已创建User角色");
        }

        // 4. 创建用户
        var user = new User
        {
            Id = Guid.NewGuid(),
            Username = dto.Username,
            Password = hashedPwd,
            Email = dto.Email ?? string.Empty,
            Phone = dto.Phone,
            IsActive = true,
            CreatedAt = DateTime.UtcNow,
            UpdatedAt = DateTime.UtcNow
        };

        // 5. 分配默认角色
        user.AssigRole(defaultRole);

        // 6. 保存用户
        await _userRepo.CreateAsync(user);
    }

    public async Task<LoginResultDto> LoginAsync(string username, string password)
    {
        var user = (await _userRepo.GetAllAsync()).FirstOrDefault(u => u.Username == username);
        if (user == null)
        {
            return new LoginResultDto
            {
                Code = 400,
                Msg = "账号不存在，请确认后重试"
            };
        }

        var hashedPwd = HashPassword(password);
        if (user.Password != hashedPwd)
        {
            return new LoginResultDto
            {
                Code = 400,
                Msg = "账号或者密码无效，请确认后重试"
            };
        }

        // 生成JWT令牌
        var token = _jwtService.GenerateToken(user.Id, username);

        // 构建用户信息
        var userInfo = new UserInfo
        {
            Id = user.Id,
            Username = user.Username,
            Email = user.Email,
            CreatedAt = user.CreatedAt,
            IsActive = user.IsActive
        };

        return new LoginResultDto
        {
            Code = 200,
            Msg = "登录成功",
            Token = token,
            UserInfo = userInfo
        };
    }

    private string HashPassword(string password)
    {
        // 简单示例，实际请用更安全的哈希算法
        using var sha256 = System.Security.Cryptography.SHA256.Create();
        var bytes = System.Text.Encoding.UTF8.GetBytes(password);
        var hash = sha256.ComputeHash(bytes);
        return Convert.ToBase64String(hash);
    }
}

